package com.example.cinema.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextPaint;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.example.cinema.BR;
import com.example.cinema.R;
import com.example.cinema.UserAttribute;
import com.example.cinema.adapter.CommentAdapter;
import com.example.cinema.adapter.CommentRecyAdapter;
import com.example.cinema.bindingdata.LiveItemData;
import com.example.cinema.bindingdata.LiveTypeData;
import com.example.cinema.bindingdata.MovieData;
import com.example.cinema.databinding.ActivityLivelistBinding;
import com.example.cinema.drawview.LivePlayerVideo;
import com.example.cinema.drawview.ShortPlayerVideo;
import com.example.cinema.request.RequestData;
import com.example.cinema.request.RequestSend;

import java.util.ArrayList;
import java.util.List;

public class ActivtyLiveList extends AppCompatActivity {


    @Override
    protected void onPause() {
        super.onPause();
        if (LivePlayerVideo != null) {
            LivePlayerVideo.Playstop();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (LivePlayerVideo != null) {
            LivePlayerVideo.Playstart();
        }
    }

    private ActivityLivelistBinding ALL;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ALL = DataBindingUtil.setContentView(this, R.layout.activity_livelist);
        init();
        if(Build.VERSION.SDK_INT>11 && Build.VERSION.SDK_INT<19)
        {
            View view = getWindow().getDecorView();
            view.setSystemUiVisibility(View.GONE);
        }else if(Build.VERSION.SDK_INT>=19){
            View view = getWindow().getDecorView();
            int UIOP = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY|View.SYSTEM_UI_FLAG_FULLSCREEN;
            view.setSystemUiVisibility(UIOP);
        }
    }

    private CommentAdapter gridAdapter;
    private List<LiveItemData> listdata = new ArrayList<>();
    private UserAttribute attribute;
    private List<LiveTypeData> typeData;

    private int postionsele = 0;
    private void init() {
        Intent intent = getIntent();
        postionsele = intent.getIntExtra("postion",0);


        attribute = (UserAttribute) getApplication();
        GetLiveType();
        gridAdapter = new CommentAdapter(getApplicationContext(), listdata, R.layout.live_list_item, BR.liveitemdata);
        ALL.gridview.setAdapter(gridAdapter);
        initlistener();
    }


    private boolean aBoolean = false;

    private void initlistener() {
        //返回
        ALL.finsh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //滚动
        ALL.gridview.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == 0 && aBoolean) {
                    page++;
                    GetLiveData();
                    aBoolean = false;
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                int len = firstVisibleItem + visibleItemCount;
                if (len >= totalItemCount) {
                    aBoolean = true;

                    Log.i("HHH", "到底");
                }
            }
        });
        //点击
        ALL.gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if(attribute.isVipbool())
                {
                    String urla = listdata.get(position).plaurl.get();
                    String urlb = listdata.get(position).relay.get();
                    String img = listdata.get(position).image.get();

                    CreateDialog(urla, urlb, img);
                }else {
                    Dialog();
                }
            }
        });
        //
        //分类选项监听
        ALL.typegroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                Log.i("HHHH", checkedId + "--");
                listdata.clear();
                page = 1;
                TextView views = (TextView) group.getChildAt(checkedId);
                int ss = group.indexOfChild(views);
                TextView tvide = (TextView) group.getChildAt(ss);
                Log.i("HHHH","索引"+ss);
                int len = group.getChildCount();
                for (int i = 0; i < len; i++) {
                    TextView view = (RadioButton) group.getChildAt(i);
                    view.setTextSize(14);
                    view.setTextColor(Color.parseColor("#939393"));
                    TextPaint paint = view.getPaint();
                    paint.setFakeBoldText(false);
                }
                if(tvide!=null)
                {
                    tvide.setTextColor(Color.parseColor("#FFFFFF"));
                    tvide.setTextSize(16);
                    TextPaint paint = views.getPaint();
                    paint.setFakeBoldText(true);

                    typeid = views.getTag(R.id.typeid).toString();
                    Log.i("BBVB",typeid+"类型");
                }


                GetLiveData();
            }
        });
    }
    //获取直播分类数据
    private void GetLiveType()
    {
        new Thread()
        {
            @Override
            public void run() {
                RequestData requestData = new RequestData(getApplicationContext());
                typeData =  requestData.ReqLiveData();
                handler.sendEmptyMessage(1001);
            }
        }.start();
    }
    //获取数据
    private int page = 1;
    private int limit = 30;
    private String typeid;
    private void GetLiveData() {
        if (attribute.getUID() == null || attribute.getToken() == null) {
            Intent intent = new Intent();
            intent.setAction("sign");
            startActivity(intent);
            return;
        }
        new Thread() {
            @Override
            public void run() {
                Log.i("HAHSHDH",typeid);
                RequestData requestData = new RequestData(getApplicationContext());
                List<LiveItemData> itemData = requestData.GetLiveTypePageData(page, limit, attribute,typeid);
                listdata.addAll(itemData);
                Log.i("BBVB",listdata.size()+"数量");
                handler.sendEmptyMessage(1000);
            }
        }.start();
    }

    //弹出播放
    private AlertDialog alertDialog;
    private LivePlayerVideo LivePlayerVideo;

    private void CreateDialog(String urla, String urlb, String img) {

        int w = getResources().getDisplayMetrics().widthPixels;
        int h = getResources().getDisplayMetrics().heightPixels;
        LivePlayerVideo = new LivePlayerVideo(getApplicationContext());
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        params.height = h+500;
        params.width = w;
        LivePlayerVideo.setLayoutParams(params);

        alertDialog = new AlertDialog.Builder(ActivtyLiveList.this).create();
        alertDialog.setView(LivePlayerVideo);
        alertDialog.show();
        Window window = alertDialog.getWindow();
        window.getDecorView().setPadding(0, 0, 0, 0);
        window.getDecorView().setBackgroundColor(Color.BLACK);
        WindowManager.LayoutParams wparm = window.getAttributes();
        wparm.width = w;
        wparm.height = h;
        window.setAttributes(wparm);

        LivePlayerVideo.setImgUrl(img);
        FrameLayout.LayoutParams mparams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        mparams.height = h;
        mparams.width = w;
        mparams.gravity = Gravity.CENTER;
        LivePlayerVideo.setLayoutParams(mparams);
        LivePlayerVideo.setPlayurl(urlb);
        LivePlayerVideo.loadVideo();
        alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                if(Build.VERSION.SDK_INT>11 && Build.VERSION.SDK_INT<19)
                {
                    View view = ALL.typegroup.getRootView();
                    view.setSystemUiVisibility(View.GONE);
                }else if(Build.VERSION.SDK_INT>=19){
                    View view = ALL.typegroup.getRootView();
                    int UIOP = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY|View.SYSTEM_UI_FLAG_FULLSCREEN;
                    view.setSystemUiVisibility(UIOP);
                }
            }
        });
        alertDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                LivePlayerVideo.Playrelease();
                if(Build.VERSION.SDK_INT>11 && Build.VERSION.SDK_INT<19)
                {
                    View view = ALL.typegroup.getRootView();
                    view.setSystemUiVisibility(View.GONE);
                }else if(Build.VERSION.SDK_INT>=19){
                    View view = ALL.typegroup.getRootView();
                    int UIOP = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY|View.SYSTEM_UI_FLAG_FULLSCREEN;
                    view.setSystemUiVisibility(UIOP);
                }

            }
        });
        //视频错误回调
        LivePlayerVideo.SetOnErrorListener(new LivePlayerVideo.OnLiveEErrorListener() {
            @Override
            public void onError() {
                LivePlayerVideo.Playrelease();
                Toast.makeText(getApplicationContext(), "主播已下线！", Toast.LENGTH_SHORT).show();
                alertDialog.cancel();
                if(Build.VERSION.SDK_INT>11 && Build.VERSION.SDK_INT<19)
                {
                    View view = ALL.typegroup.getRootView();
                    view.setSystemUiVisibility(View.GONE);
                }else if(Build.VERSION.SDK_INT>=19){
                    View view = ALL.typegroup.getRootView();
                    int UIOP = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY|View.SYSTEM_UI_FLAG_FULLSCREEN;
                    view.setSystemUiVisibility(UIOP);
                }

            }
        });

        if(Build.VERSION.SDK_INT>11 && Build.VERSION.SDK_INT<19)
        {
            View view = ALL.typegroup.getRootView();
            view.setSystemUiVisibility(View.GONE);
        }else if(Build.VERSION.SDK_INT>=19){
            View view = ALL.typegroup.getRootView();
            int UIOP = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY|View.SYSTEM_UI_FLAG_FULLSCREEN;
            view.setSystemUiVisibility(UIOP);
        }

    }

    //非VIP提醒
    private AlertDialog alertDialogw;

    private void Dialog() {
        int w = getResources().getDisplayMetrics().widthPixels;
        int h = getResources().getDisplayMetrics().heightPixels;
        View view = LinearLayout.inflate(getApplicationContext(), R.layout.dialog_item, null);

        LinearLayout.LayoutParams paramsa = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        paramsa.width = w / 5 * 2;
        paramsa.height = h / 4 * 3;
        view.setLayoutParams(paramsa);
        int wi = getResources().getDisplayMetrics().widthPixels;
        alertDialogw = new AlertDialog.Builder(ActivtyLiveList.this)
                .setView(view)
                .setCancelable(false)
                .show();
        Window window = alertDialogw.getWindow();
        window.getDecorView().setPadding(0, 0, 0, 0);
        window.getDecorView().setBackgroundColor(Color.argb(0, 0, 0, 0));
        WindowManager.LayoutParams params = window.getAttributes();
        params.width = wi / 4 * 3;
        window.setAttributes(params);

        View vipview = view.findViewById(R.id.vipbtn);
        View wymf = view.findViewById(R.id.mfbtn);
        View close = view.findViewById(R.id.closebtn);
        vipview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳到VIP充值

                alertDialogw.cancel();
                Intent intent = new Intent();
                intent.setAction("cartpay");
                startActivity(intent);
            }
        });
        wymf.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳到推广分享

                alertDialogw.cancel();
                Intent intent = new Intent();
                intent.setAction("spread");
                startActivity(intent);
            }
        });
        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialogw.cancel();
            }
        });
    }

    Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            if (msg.what == 1000) {
                gridAdapter.notifyDataSetChanged();
                return;
            }
            if(msg.what == 1001)
            {
                for (int i = 0; i < typeData.size(); i++) {
                    LiveTypeData mdata = typeData.get(i);
                    RadioButton Rb = new RadioButton(getApplicationContext());
                    Rb.setButtonDrawable(null);
                    Rb.setText(mdata.typename.get());
                    Rb.setTextColor(Color.parseColor("#939393"));
                    Rb.setTextSize(14);
                    Rb.setId(i);
                    Rb.setTag(R.id.typeid, mdata.typetid.get());
                    Log.i("FFFFD", mdata.typetid.get());
                    Rb.setPadding(30, 2, 30, 2);
                    Rb.setBackgroundColor(Color.parseColor("#00000000"));
                    ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                    ALL.typegroup.addView(Rb);
                }
                ALL.typegroup.check(postionsele);
            }
        }
    };
}
